package com.qyhl.webtv.module_news.news.jlnews;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;
import com.just.library.WebDefaultSettingsManager;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.JLNewDetailBean;
import com.qyhl.webtv.commonlib.utils.MJavascriptInterface;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.share.ShareUtils;
import com.qyhl.webtv.commonlib.utils.view.MyWebView;
import com.qyhl.webtv.commonlib.utils.view.video.detailvideo.QYVideoPlayer;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;

import butterknife.BindView;

@Route(path = ARouterPathConstant.JL_NEWS)
public class JLNewsDetailActivity extends BaseActivity implements JLNewsContract.JLNewsView {
    @BindView(R2.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R2.id.toolbar_layout)
    Toolbar toolbarLayout;
    @BindView(R2.id.video_player)
    QYVideoPlayer videoPlayer;
    @BindView(R2.id.title_news)
    TextView mTitle;
    @BindView(R2.id.scan)
    TextView scan;
    @BindView(R2.id.publish_date)
    TextView publishDate;
    @BindView(R2.id.origin_writer)
    TextView originWriter;
    @BindView(R2.id.summary)
    TextView summary;
    @BindView(R2.id.webview)
    MyWebView webview;
    @BindView(R2.id.web_layout)
    LinearLayout webLayout;
    @BindView(R2.id.share_wechat)
    TextView shareWechat;
    @BindView(R2.id.share_circle)
    TextView shareCircle;
    @BindView(R2.id.share_qq)
    TextView shareQq;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    @Autowired(name = "id")
    String newsId;

    private JLNewsPresenter mPresenter;

    private JLNewDetailBean mBean;

    private WebView mWebView;

    private int index = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbarLayout);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_jl_news;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new JLNewsPresenter(this);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
    }


    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter.getDetail(newsId);
    }

    private void setListeners() {
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getDetail(newsId);
        });

        shareCircle.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(JLNewsDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                ShareUtils.getInstance().goSingleShare("Circle", newsId, 23, mBean.getBrief(), mBean.getTitle(), mBean.getIndex_pic(), JLNewsDetailActivity.this);
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(JLNewsDetailActivity.this);
            }
        }));

        shareQq.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(JLNewsDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                ShareUtils.getInstance().goSingleShare("QQ", newsId, 23, mBean.getBrief(), mBean.getTitle(), mBean.getIndex_pic(), JLNewsDetailActivity.this);
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(JLNewsDetailActivity.this);
            }
        }));

        shareWechat.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(JLNewsDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                ShareUtils.getInstance().goSingleShare("WeiXin", newsId, 23, mBean.getBrief(), mBean.getTitle(), mBean.getIndex_pic(), JLNewsDetailActivity.this);
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(JLNewsDetailActivity.this);
            }
        }));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (GSYVideoManager.backFromWindowFull(JLNewsDetailActivity.this)) {
                return true;
            } else if (webview != null && webview.canGoBack()) {
                webview.goBack();
            } else if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                finish();
            }
            return true;
        } else if (item.getItemId() == R.id.more) {
            if (mBean != null) {
                MShareBoard shareBoard = new MShareBoard(JLNewsDetailActivity.this, newsId, mBean.getTitle(), mBean.getIndex_pic(), mBean.getBrief(), CommonUtils.getInstance().getBannerId(), 23, false, false);
                shareBoard.setToolListener(new MShareBoard.ShareToolListener() {
                    @Override
                    public void collectChange(boolean isCollect) {

                    }

                    @Override
                    public void textSizeChange() {
                        int checkId;
                        switch (SpfManager.getInstance(JLNewsDetailActivity.this).getInt("fontSize", 2)) {
                            case 0:
                                checkId = R.id.textsize_lv1;
                                break;
                            case 1:
                                checkId = R.id.textsize_lv2;
                                break;
                            case 2:
                                checkId = R.id.textsize_lv3;
                                break;
                            case 3:
                                checkId = R.id.textsize_lv4;
                                break;
                            case 4:
                                checkId = R.id.textsize_lv5;
                                break;
                            default:
                                checkId = R.id.textsize_lv3;
                                break;
                        }
                        new OtherDialog.Builder(JLNewsDetailActivity.this)
                                .setContentView(R.layout.news_dialog_textsize_choice)
                                .setWidth(0.8f)
                                .setCanceledOnTouchOutside(true)
                                .setOnCheckedChangeListener(R.id.dialog_radioGroup, checkId, position -> {
                                    SpfManager.getInstance(JLNewsDetailActivity.this).putInt("fontSize", idToPosition(position));
                                    setFontSize(idToPosition(position));
                                })
                                .setDismissButton(R.id.dialog_cancel)
                                .show();
                    }
                });
                shareBoard.showPopupWindow();
            }

        }
        return super.onOptionsItemSelected(item);
    }

    private int idToPosition(int checkId) {
        int pos = 2;
        if (checkId == R.id.textsize_lv1) {
            pos = 0;
        } else if (checkId == R.id.textsize_lv2) {
            pos = 1;
        } else if (checkId == R.id.textsize_lv3) {
            pos = 2;
        } else if (checkId == R.id.textsize_lv4) {
            pos = 3;
        } else if (checkId == R.id.textsize_lv5) {
            pos = 4;
        }
        return pos;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.news_detail_mores, menu);
        return true;
    }

    /**
     * 设置webview字体大小
     */
    private void setFontSize(int position) {
        switch (position) {
            case 0:
                webview.getSettings().setTextZoom(50);
                break;
            case 1:
                webview.getSettings().setTextZoom(75);
                break;
            case 2:
                webview.getSettings().setTextZoom(100);
                break;
            case 3:
                webview.getSettings().setTextZoom(150);
                break;
            case 4:
                webview.getSettings().setTextZoom(200);
                break;
            default:
                break;
        }
    }

    //展示内容
    private void showContent(String content) {
        initWebView();
        if (StringUtils.isNotEmpty(content)) {
            String htmlString = getNewContent(content);
            Log.i("@@@", htmlString);
            webview.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
            webview.addJavascriptInterface(new MJavascriptInterface(this, StringUtils.returnImageUrlsFromHtml(htmlString)), "imagelistener");
            webview.setWebViewClient(new MyWebViewClient());
            removeWebViewJI(webview);
        } else {
            setError();
        }

    }


    //Web视图
    class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webview.getSettings().setBlockNetworkImage(true);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            /*
             * 非wifi下不加载图片
             */
            if (NetUtil.isWifi(JLNewsDetailActivity.this)) {
                webview.getSettings().setBlockNetworkImage(false);
            } else {
                if (SpfManager.getInstance(JLNewsDetailActivity.this).getBoolean("noPicture", false)) {
                    webview.getSettings().setBlockNetworkImage(true);
                } else {
                    webview.getSettings().setBlockNetworkImage(false);
                }
            }
            //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            //重新测量
            webview.measure(w, h);
            addImageClickListener(view);
        }

        @JavascriptInterface
        public void addImageClickListener(WebView webView) {
            webView.loadUrl(
                    "javascript:(function(){"
                            + "  var objs = document.getElementsByTagName(\"img\"); "
                            + "  for(var i=0;i<objs.length;i++){"
                            + "     objs[i].onclick=function(){"
                            + "          window.imagelistener.openImage(this.src);  "
                            + "     }"
                            + "  }"
                            + "})()");
        }
    }

    //初始化webview
    private void initWebView() {
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDefaultTextEncodingName("utf-8");
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setFontSize(SpfManager.getInstance(this).getInt("fontSize", 2));
        webview.getSettings().setBlockNetworkImage(true);
    }

    //webview中的图片自适应大小
    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("style", "max-width:100%;height:auto;");
        }
        doc.select("div.titleDivs").remove();
        Log.i("VACK", doc.toString());
        return doc.toString();
    }


    @Override
    public void setDetail(JLNewDetailBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mBean = bean;
        switch (bean.getNewsType()) {
            case "JLCommonNews":
                videoPlayer.setVisibility(View.GONE);
                mTitle.setVisibility(View.VISIBLE);
                mTitle.setText(bean.getTitle());
                webview.setVisibility(View.VISIBLE);
                if (StringUtils.isNotEmpty(bean.getContent())) {
                    showContent(bean.getContent());
                }
                break;
            case "JLVideoNews":
                videoPlayer.setVisibility(View.VISIBLE);
                webview.setVisibility(View.VISIBLE);
                ImageView imageView = new ImageView(this);
                Glide.with(this)
                        .load(bean.getIndex_pic())
                        .apply(new RequestOptions().error(R.drawable.cover_video_default))
                        .into(imageView);
                videoPlayer.setThumbImageView(imageView);

                videoPlayer.setRotateViewAuto(false);
                videoPlayer.setLockLand(true);
                videoPlayer.setUp(mBean.getUrl() == null ? "" : mBean.getUrl(), true, "");
                videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                        videoPlayer.startWindowFullscreen(JLNewsDetailActivity.this, true, true);
                    }
                });
                videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (GSYVideoManager.backFromWindowFull(JLNewsDetailActivity.this)) {

                        } else {
                            finish();
                        }
                    }
                });
                mTitle.setVisibility(View.VISIBLE);
                mTitle.setText(bean.getTitle());
                if (StringUtils.isNotEmpty(bean.getContent())) {
                    showContent(bean.getContent());
                }
                break;
            case "JLOutNews":
                mTitle.setVisibility(View.GONE);
                videoPlayer.setVisibility(View.GONE);
                toolbarTitle.setText(bean.getTitle());
                webview.setVisibility(View.GONE);

                WebViewClient mWebViewClient = new WebViewClient() {
                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        handler.cancel();
                    }

                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        if (url.startsWith("http:") || url.startsWith("https:")) {
                            return false;
                        }
                        try {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                            startActivity(intent);
                        } catch (Exception e) {
                        }
                        return true;
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        loadMask.setStatus(LoadingLayout.Success);
                        if (index == 0) {
                            index++;
                            mWebView.reload();
                        }
                    }
                };

                AgentWeb mAgentWeb = AgentWeb.with(this)
                        .setAgentWebParent(webLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                        .useDefaultIndicator()
                        .defaultProgressBarColor() // 使用默认进度条颜色
                        .setWebSettings(new CustomSettings())
                        .setWebViewClient(mWebViewClient)
                        .setReceivedTitleCallback(new ChromeClientCallbackManager.ReceivedTitleCallback() {
                            @Override
                            public void onReceivedTitle(WebView view, String title) {

                            }
                        })//设置 Web 页面的 title 回调
                        .createAgentWeb()//
                        .ready()
                        .go(bean.getOutlink());

                mWebView = mAgentWeb.getWebCreator().get();
                break;
        }

        //设置描述
        if (StringUtils.isNotEmpty(mBean.getBrief())) {
            summary.setVisibility(View.VISIBLE);
            summary.setText(mBean.getBrief());
        } else {
            summary.setVisibility(View.GONE);
        }

        originWriter.setText(mBean.getColumn_name());

        //设置发布时间
        publishDate.setText(DateUtils.detailDateTranslate(mBean.getCreated_at()));

        //设置浏览数
        try {
            int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
            if (minPlay == 0) {
                scan.setVisibility(View.GONE);
            } else {
                //判断评论数是否大于最少浏览数
                if (mBean.getClicks() >=
                        minPlay) {
                    scan.setText(StringUtils.transformNum(mBean.getClicks() + ""));
                    scan.setVisibility(View.VISIBLE);
                } else {
                    scan.setVisibility(View.GONE);
                }
            }

        } catch (Exception e) {
            scan.setVisibility(View.GONE);
        }


    }

    @Override
    public void setError() {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setErrorText("获取详情失败！");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (videoPlayer != null) {
            videoPlayer.onVideoResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (videoPlayer != null) {
            videoPlayer.onVideoPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (videoPlayer != null) {
            videoPlayer.release();
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (GSYVideoManager.backFromWindowFull(this)) {
                    return true;
                } else if (webview != null && webview.canGoBack()) {
                    webview.goBack();
                } else if (mWebView != null && mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    class CustomSettings extends WebDefaultSettingsManager {
        private CustomSettings() {
            super();
        }


        @Override
        public com.just.library.WebSettings toSetting(WebView webView) {
            super.toSetting(webView);
            String path = Environment.getExternalStorageDirectory().getPath() + "/baidudata";//百度地图调用需要
            File tmpFile = new File(path);
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            getWebSettings().setGeolocationDatabasePath(path);
            getWebSettings().setDomStorageEnabled(true);
            getWebSettings().setBlockNetworkImage(false);//是否阻塞加载网络图片  协议http or https
            getWebSettings().setAllowFileAccess(false); //允许加载本地文件html  file协议, 这可能会造成不安全 , 建议重写关闭
            getWebSettings().setAllowFileAccessFromFileURLs(false); //通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
            getWebSettings().setAllowUniversalAccessFromFileURLs(false);//允许通过 file url 加载的 Javascript 可以访问其他的源，包括其他的文件和 http，https 等其他的源
            getWebSettings().setUseWideViewPort(true);
            getWebSettings().setSupportZoom(true);
            getWebSettings().setBuiltInZoomControls(true);
            setFontSize(SpfManager.getInstance(JLNewsDetailActivity.this).getInt("fontSize", 2));
            return this;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
